package cn.itcast.utils;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

public class My_DataSource implements DataSource {
    private static List<Connection> pool = Collections.synchronizedList(new ArrayList<Connection>());
    //获取十个连接
    static {
        for (int i = 1; i <= 10; i++){
            Connection conn = JDBCUtil.getConn();
            pool.add(conn);
        }
    }

    //连接池中的连接的个数
    public int getSize(){
        return pool.size();
    }

    @Override
    public Connection getConnection() throws SQLException {
        if (pool.size()>0){
          Connection  conn = pool.remove(0);

            Connection proxyConn = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[]{Connection.class}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("close".equals(method.getName())){
                        pool.add(conn);
                        return null;
                    }else{
                        return method.invoke(conn,args);
                    }

                }
            });

         return proxyConn;
        }else{
            throw  new RuntimeException("连接已经用尽");
        }

    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
